package cn.topcodes.tcsf.cms.web.controller;

import cn.topcode.unicorn.utils.CollectionUtil;
import cn.topcode.unicorn.utils.JsonUtil;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcode.unicorn.utils.ValidationUtil;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.cms.domain.entity.Album;
import cn.topcodes.tcsf.cms.domain.entity.AlbumCatalog;
import cn.topcodes.tcsf.cms.domain.entity.AlbumPicture;
import cn.topcodes.tcsf.cms.domain.form.AlbumForm;
import cn.topcodes.tcsf.cms.domain.vo.AlbumVo;
import cn.topcodes.tcsf.cms.domain.vo.StaticFilesVo;
import cn.topcodes.tcsf.cms.service.AlbumCatalogService;
import cn.topcodes.tcsf.cms.service.AlbumPictureService;
import cn.topcodes.tcsf.cms.service.AlbumService;
import cn.topcodes.tcsf.cms.service.ConfigService;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Album管理控制器
 *
 * @author Yvan
 * @date 2018-02-09 10:46:26
 */
@Controller
@RequestMapping("/admin/cms/album")
public class AlbumController extends AdminController<Album, AlbumVo, AlbumForm> {

    @Autowired
    private AlbumService albumService;

    @Autowired
    private AlbumPictureService albumPictureService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private AlbumCatalogService albumCatalogService;

    @Override
    protected String getPageFolder() {
        return "/cms/album";
    }

    @Override
    public ApiResponseEntity create(HttpServletRequest request,
                                    @Valid @ApiParam("创建资源表单") AlbumForm form,
                                    BindingResult result) {
        ValidationUtil.validate(result);
        Album entity = this.form2Entity(form);
        Long id = albumService.create(entity);
        albumPictureService.createOrUpdate(id, form.getContentImg());
        return ApiResponseEntity.buildOK().setBody(id);
    }

    @Override
    public ApiResponseEntity<Void> update(HttpServletRequest request,
                                          @Valid @ApiParam("更新资源表单") AlbumForm form,
                                          BindingResult result) {
        ValidationUtil.validate(result);
        Album entity = this.form2Entity(form);
        albumService.update(entity);
        albumPictureService.createOrUpdate(entity.getId(), form.getContentImg());
        return ApiResponseEntity.buildOK();
    }

    @Override
    protected void entity2VoDiff(Album entity, AlbumVo vo) {
        AlbumCatalog albumCatalog = albumCatalogService.findOne(entity.getCatalogId());
        vo.setCatalogName(albumCatalog == null ? null : albumCatalog.getName());
        Example example = albumPictureService.buildExample();
        example.or().andEqualTo(AlbumPicture.FIELD_ALBUMID, entity.getId());
        List<AlbumPicture> albumPictures = albumPictureService.findAll(example);
        if (null != albumPictures && !albumPictures.isEmpty()) {
            vo.setPictureCount(albumPictures.size());
            List<String> paths = new ArrayList<>();
            for (AlbumPicture albumPicture : albumPictures) {
                paths.add(OtherController.FILE_PATH + "?path=" + albumPicture.getUrl());
            }
            vo.setPictures(paths);
        } else {
            vo.setPictureCount(0);
        }
        super.entity2VoDiff(entity, vo);
    }

    @Override
    public String update(Long id, HttpServletRequest request, Model model) {

        Album album = albumService.findOne(id);
        AlbumVo albumVo = new AlbumVo();
        Long catalogId = album.getCatalogId();
        AlbumCatalog albumCatalog = albumCatalogService.findOne(catalogId);

        albumVo.setId(album.getId());
        albumVo.setCatalogId(album.getCatalogId());
        albumVo.setDescription(album.getDescription());
        albumVo.setName(album.getName());
        albumVo.setCatalogName(albumCatalog.getName());


        Example example = albumPictureService.buildExample();
        example.or().andEqualTo(AlbumPicture.FIELD_ALBUMID, album.getId());
        List<AlbumPicture> albumPictures = albumPictureService.findAll(example);
        List<String> collect = albumPictures.stream().map(e -> e.getUrl()).collect(Collectors.toList());
        String contentImg = CollectionUtil.array2String(collect);
        albumVo.setContentImg(contentImg);
        List<StaticFilesVo> staticFilesVos = new ArrayList<>();
        if (StringUtil.isNotBlank(contentImg)) {
            String[] imgs = contentImg.split(",");
            for (String img : imgs) {
                File file = new File(configService.getFileFolderPath() + img);
                if (file.exists()) {
                    StaticFilesVo staticFilesVo = new StaticFilesVo();
                    staticFilesVo.setOrigSize(file.length());
                    staticFilesVo.setSize(file.length());
                    staticFilesVo.setLastModifiedDate(new Date(file.lastModified()));
                    staticFilesVo.setType("image/jpeg");
                    staticFilesVo.setId(file.getName());
                    staticFilesVo.setName(file.getName());
                    staticFilesVo.setPreviewImage(OtherController.FILE_PATH + "?path=" + img);
                    staticFilesVos.add(staticFilesVo);
                }
            }
        }
        model.addAttribute("entity", albumVo);
        model.addAttribute("staticFile", JsonUtil.toJson(staticFilesVos));
        return this.getPageFolder() + "/update";
    }

    @RequestMapping(value = "updateContentImg")
    @ResponseBody
    public ApiResponseEntity updateContentImg(@RequestParam(value = "id") Long id,
                                              @RequestParam(value = "content") String content,
                                              HttpServletResponse response) throws IOException {
        Album album = this.albumService.findOneOrFail(id);
        Example example = albumPictureService.buildExample();
        example.or()
                .andEqualTo(AlbumPicture.FIELD_ALBUMID, album.getId());
        List<AlbumPicture> albumPictures = albumPictureService.findAll(example);

        List<AlbumPicture> collect = albumPictures.stream()
                .filter(albumPicture -> albumPicture.getUrl().contains(content))
                .collect(Collectors.toList());
        if (null != collect && !collect.isEmpty()) {
            AlbumPicture albumPicture = collect.get(0);
            albumPictureService.delete(albumPicture.getId());
        }

        List<String> strings = albumPictures.stream()
                .filter(albumPicture -> !albumPicture.getUrl().contains(content))
                .map(e -> e.getUrl())
                .collect(Collectors.toList());
        return ApiResponseEntity.buildOK().setBody(CollectionUtil.array2String(strings));
    }
}
